"""redis连接池"""
import json
from threading import Lock
from typing import Union

import redis


class RedisPool:
    __redis_pool = None
    __lock = Lock()

    def __init__(self, db, config: dict):
        self.host = config.get('host')
        self.port = config.get('port')
        self.db = db
        self.password = config.get('password')
        self.redis_pool = self.__connect()
        if self.redis_pool:
            self.conn = redis.StrictRedis(
                connection_pool=self.redis_pool)

    def __connect(self):
        with self.__lock:
            if not self.__redis_pool:
                self.__redis_pool = redis.ConnectionPool(
                    host=self.host, port=self.port, db=self.db, password=self.password, decode_responses=True)  # noqa:E501
        return self.__redis_pool

    def value_deduplicate(self, name, value):
        """值去重"""
        result = self.conn.sadd(name, value)
        return result != 0

    def get_value(self, name):
        """获取值"""
        return self.conn.get(name)

    def get_list(self, name) -> Union[dict, None]:
        """获取列表"""
        result = self.conn.lpop(name)
        return json.loads(result) if result else None  # type: ignore # noqa:E501

    def set_list(self, name, value: dict):
        """设置列表"""
        return self.conn.rpush(name, json.dumps(value))
